<?php
class Shop_Model_HasCategory extends Promotor_Model_Scaffold {

	protected $_dbTableClass = 'Shop_Model_DbTable_HasCategory';
	
	protected $_observers = array(
		'post_editableUpdate' => true
	);
	
	public function selectList() {
		$db = $this->getDbTable()
				   ->getAdapter();

		$select = new Zend_Db_Select($db);
		
		$select->from(array('shc' => 'shop_has_category'))
			   ->joinInner(
			   		array('sp' => 'shop_product'),
			   		'shc.product_id = sp.id',
			   		array(
			   			'product' => 'name')
			   	)
			   	->joinLeft(
			   		array('sc' => 'shop_category'),
			   			'sc.id = shc.category_id', array('category' => 'name'));
			   		
		return $select;
	}
	
	/**
	 * @param integer $productId
	 * @param array $categories
	 * @return void
	 */
	public function attacheProductToCategory($productId, array $categories) {
		$table = $this->getDbTable();
		$db = $table->getAdapter();
		
		// filtrowanie przed zduplikowanymi kluczami!
		$categories = array_keys(array_flip($categories));

		$db->beginTransaction();
		$table->delete($db->quoteInto('product_id = ?', $productId));
		try {
			foreach ($categories as $categoryId) {
				if (!is_numeric($categoryId)) {
					continue;
				}
				$table->insert(array(
					'product_id' => $productId,
					'category_id' => $categoryId
				));
			}
			$db->commit();
			$this->_setStatus(self::SUCCESS);
		} catch (Zend_Db_Exception $e) {
			$db->rollBack();
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);
		}
	}
}